<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Validate;
use app\util\Utils;
use think\Db;
use app\admin\model\Code;
use app\api\model\Item;
use app\api\model\ItemImg;
use app\api\model\ItemProcess;
use think\Cache;

class ClifeController extends Controller {
    /*
     * 这是2020年写给和而泰的接口 用于对接智慧场景
     * 调用方法为 clife调用JAVA调用PHP
     * 所以此接口不需要做接口验证
     */

    /*
     * code列表
     */

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 3  请求黑名单
         * 4  token无效
         * 1001  令牌授权错误
         * 8001  请求参数错误
         * 9999  其它错误
         * 
         * 2002  没有发现此项目  
         * 2003  此项目已经下架 
         * 2004  
         * 2005  
         */
    }

    /*
     * 返回数据
     */

    public static function ajaxReturn($code, $msg, $data) {
        $return = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];

        return $return;
    }
    
    /*
     * 获取access Token
     */
    public function getAccessToken(){
        //防止java保存的token失效 直接调用java接口获取token
        $url = "https://daping.dwkkm.com/hert/api/room/getToken";
        $result = Utils::curlGet($url);
        $result = json_decode($result,true);
//        print_r($result);
        return $result['data'];
        
//        $app_production = config('clifeconfig.app_production');
//        if($app_production){
//            $tokenPath = config('clifeconfig.OpenToken');
//        }  else {
//            $tokenPath = config('clifeconfig.ItestToken');
//        }
//        $appId = config('clifeconfig.appid');
//        $appSecret = config('clifeconfig.appSecret');
//        $url = $tokenPath.'?appId='.$appId.'&appSecret='.$appSecret.'&timestamp='.time()*1000;
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_HEADER, 0);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        $result = curl_exec($ch);
//        curl_close($ch);
//        $result = json_decode($result,TRUE);
//        $result = $result['data']['accessToken'];
//        return $result;
    }
    
    /*
     * 生成签名
     * $array 必须包含accessToken
     * 将请求方法+请求地址+所有参数按照参数名的字母顺序升序排序后拼接+appSecret 
     * 将第1步的结果MD5后生成签名参数sign。（签名后的MD5需要转换成小写）
     * 
     * 请求方法为GET或POST，注意大写。 
     * 请求地址为客户端请求完整地址，如：http://open.api.clife.cn/v1/data/get 
     * 参数拼接，按照参数名的字母顺序升序排序后进行拼接，如：accessToken=xxx&appId=xxx&name1=value1&name2=value2& 
     * 组成完整的拼接，如：GEThttp://open.api.clife.cn/v1/data/getaccessToken=xxx&appId=xxx&name1=value1&name2=value2&appSecret 
     * 生成MD5值，如：74b024f42f3075c4c06e4e8f22ca7a5f
     */

    public function sign($url,$method,$array) {
//        $array = array_merge($array, $token);
        ksort($array);
        $string = "";
        while (list($key, $val) = each($array)) {
            $string = $string . $key . '=' . $val . '&';
        }
        $string = substr($string, 0, strlen($string) - 1);
        $appSecret = config('clifeconfig.appSecret');
        $string = $method.$url.$string.'&'.$appSecret;
//        return $string;
        return md5($string);
    }
    
    public function ces(){
        $url = 'http://www.baidu.com';
        $method = 'POST';
        $array = ['a'=>666,'b'=>999];
        return $this->sign($url, $method, $array);
    }


    /*
     * 项目同步
     * 作者 xfwed
     * 日期 2020-11-11
     * 
     * 
     */
    public function itemSync(){
        $app_production = config('clifeconfig.app_production');
        if($app_production){
            $apiPath = config('clifeconfig.OpenApiPath');
        }  else {
            $apiPath = config('clifeconfig.ItestApiPath');
        }
        $apiPath = $apiPath.'open/service/serviceSync';
        $itemId = input('param.itemId');
        $itemRow = Item::where('id',$itemId)
                ->field('id projectCode,item_name name,special_money privilegePrice,item_price price,service_time duration,is_del isShelf,vice_name introduction,xcx_img projectQrCode')
                ->find();
        if($itemRow['isShelf'] == 2){
            $itemRow['isShelf'] = 0;
        }
        $key = 'itemid'.$itemId;
        $name = Cache::get($key);
        if ($name) {
             $xcx_img = $name;
        } else {
            //生成项目二维码
            $ApiPath = config('appconfig.ApiPath');
            $postFields['param'] = 'a='.$itemId.'&s=0';
            $postFields['url'] = 'packageA/pages/project/projectDetail/index';
            $relust = Utils::curlPost($ApiPath . '/weChat/getWeChatCodeForUrl/',json_encode($postFields));
            $IndexPath = config('appconfig.IndexPath');
            $relust = json_decode($relust, true)['data'];
            $arr = explode(",", $relust);
            $last = $arr[1];
            $postFields1['img'] = $last;
            $postFields1['modeName'] = 'itemqrcode';
            $relust = Utils::curlPost1($IndexPath.'Public/uploadBase64Img/',$postFields1);
            $relust = json_decode($relust, true)['data'];

            Cache::set($key, $relust);
            $xcx_img = $relust;
        }
        $itemRow['projectQrCode'] = $xcx_img;
        
        $itemRow['newUserPrice'] = 990;
        $itemimg = ItemImg::where('item_id',$itemId)->column('img');
        $itemimg = implode(',',$itemimg);
        $itemRow['imageUrl'] = $itemimg;
        $itemRow['detailPicUrl']='';
        $itemRow['efficacy']='';
        $serviceJson = json_encode($itemRow,320);

        $data['appId'] = config('clifeconfig.appid');
        $data['accessToken'] = $this->getAccessToken();
        $data['timestamp'] = time()*1000;
        $data['phone'] = '4008013680';
        $data['serviceJson'] = $serviceJson;
        $method = 'POST';
        
        $data['sign'] = $this->sign($apiPath, $method, $data);
        $result = Utils::curlPost1($apiPath, $data);
        $result = json_decode($result, true);
        return $result;
    } 
    
    /*
     * 项目流程同步
     * 作者 xfwed
     * 日期 2020-12-03
     * 
     * 
     */
    public function itemProcessSync(){
        $app_production = config('clifeconfig.app_production');
        if($app_production){
            $apiPath = config('clifeconfig.OpenApiPath');
        }  else {
            $apiPath = config('clifeconfig.ItestApiPath');
        }
        $apiPath = $apiPath.'open/service/processSync';
        $processId = input('param.processId');//流程id
        $action = input('param.action');//流程具体操作模式(1=添加或者修改，0=删除)
        
        $processRow = ItemProcess::where('id',$processId)
                ->field('id processCode,name,good_id productCode,minute duration,content introduction,img imageUrl,item_id projectCode')
                ->find();
        $processRow['duration'] = $processRow['duration']*60;
        $data['projectCode'] = $processRow['projectCode'];
        unset($processRow['projectCode']);
        $processJson = json_encode($processRow,320);

        $data['appId'] = config('clifeconfig.appid');
        $data['accessToken'] = $this->getAccessToken();
        $data['timestamp'] = time()*1000;
        $data['processJson'] = $processJson;
        $data['phone'] = '4008013680';
        $data['action'] = $action;
        $method = 'POST';
        $data['sign'] = $this->sign($apiPath, $method, $data);
        //print_r($apiPath);
        //var_dump($data);
        $result = Utils::curlPost1($apiPath, $data);
        $result = json_decode($result, true);
        return $result;
    } 
    
    /*
     * 产品同步
     * 作者 xfwed
     * 日期 2020-12-03
     * 
     * 
     */
    public function goodsSync(){
        $app_production = config('clifeconfig.app_production');
        if($app_production){
            $apiPath = config('clifeconfig.OpenApiPath');
        }  else {
            $apiPath = config('clifeconfig.ItestApiPath');
        }
        $apiPath = $apiPath.'open/product/productSync';
        
        $goodsId = input('param.goodsId');//产品id
     
        $goodsRow = Db::table('goods_info')->where('id',$goodsId)
                ->field('id productCode,name,valid isShelf,summary introduction,product_ingredient ingredient,product_efficacy efficacy,xcx_img productQrCode')
                ->find();
        if($goodsRow['isShelf'] ==2 || $goodsRow['isShelf'] == 3){
            $goodsRow['isShelf'] = 0;
        }
        //商品价格
        $goodsDetail = Db::table('goods_info_detail')->where('goodsId',$goodsId)
                ->field('price privilegePrice,oriPrice price')
                ->order('price asc')
                ->find();
        $goodsRow['privilegePrice'] = $goodsDetail['privilegePrice'];
        $goodsRow['price'] = $goodsDetail['price'];
        //产品图片
        $goodsImg = Db::table('goods_images')
                ->where('goods_id',$goodsId)
                ->where('type',1)
                ->column('images');
        $goodsImg = implode(',',$goodsImg);
        $goodsRow['imageUrl'] = $goodsImg;
        $goodsRow['detailPicUrl'] = Db::table('goods_images')
                ->where('goods_id',$goodsId)
                ->where('type',2)
                ->value('images'); 
        //新人优惠价==现价
        $goodsRow['newUserPrice'] = $goodsRow['privilegePrice'];
        $goodsRow['model'] = '';
        $productJson = json_encode($goodsRow,320);

        $data['appId'] = config('clifeconfig.appid');
        $data['accessToken'] = $this->getAccessToken();
        $data['timestamp'] = time()*1000;
        $data['productJson'] = $productJson;
        $data['phone'] = '4008013680';
        $method = 'POST';
        $data['sign'] = $this->sign($apiPath, $method, $data);
//      print_r($data);
//      var_dump($data);
        $result = Utils::curlPost1($apiPath, $data);
        $result = json_decode($result, true);
        return $result;
    } 

    
    /*
     * 项目详情
     * 作者 xfwed
     * 日期 2020-10-26
     *
     * @param number itemId 项目id
     */

    public function itemInfo() {
        $rule = [
            'itemId' => 'require',
            'robot_no' => 'require',
        ];
        $msg = [
            'itemId.require' => '项目ID必须',
            'robot_no.require' => '机器编码必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }

        $itemId = $all['itemId'];  
        $robot_no = $all['robot_no'];  
        
        $row = Item::where('id',$itemId)->find();
        if(empty($row)){
            return $this->ajaxReturn(8002, '没有发现此项目', null);  
        }
        if($row['is_del'] == 2){
            return $this->ajaxReturn(8003, '此项目已经下架', null);  
        }
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',4)
                ->where('robot_no',$robot_no)
                ->value('store_id');
        
        $itemRow = Item::where('id',$itemId)
                ->field('item_name,vice_name,item_price,special_money,item_img,people,service_time,content,xcx_img')
                ->find();
        $key = $itemId.'_'.$storeId;
        $name = Cache::get($key);
        if ($name) {
             $xcx_img = $name;
        } else {
            //生成项目二维码
            $ApiPath = config('appconfig.ApiPath');
            $postFields['param'] = 'a='.$itemId.'&s='.$storeId;
            $postFields['url'] = 'packageA/pages/project/projectDetail/index';
            $relust = Utils::curlPost($ApiPath . '/weChat/getWeChatCodeForUrl/',json_encode($postFields));
            $IndexPath = config('appconfig.IndexPath');
            $relust = json_decode($relust, true)['data'];
            $arr = explode(",", $relust);
            $last = $arr[1];
            $postFields1['img'] = $last;
            $postFields1['modeName'] = 'itemqrcode';
            $relust = Utils::curlPost1($IndexPath.'Public/uploadBase64Img/',$postFields1);
            $relust = json_decode($relust, true)['data'];

            Cache::set($key, $relust);
            $xcx_img = $relust;
        }
        $itemRow['xcx_img'] = $xcx_img;
        //查询项目图片
        $itemimg = ItemImg::where('item_id',$itemId)->field('img')->select();
        $itemRow['itemimg'] = $itemimg;
        //查询项目流程
        $itemprocess = ItemProcess::alias('i')
                ->join(['goods_info'=>'g'],'g.id = i.good_id','left')
                ->where('i.item_id',$itemId)
                ->where('i.is_del',2)
                ->order('i.sort asc')
                ->field('i.sort,i.name,i.minute,i.facility,i.content,i.img,g.name gname,g.icon gicon')
                ->select();
        $itemRow['itemprocess'] = $itemprocess;
        return $this->ajaxReturn(0, '查询成功',$itemRow);
    }
    
}

?>